import { constantRouterMap } from '@/router/routers'
import Layout from '@/layout/Layout'

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    storeRoutes: [],
    firstRoutes: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
      // 初始化收藏夹
      const arr = state.routers.filter((item) => {
        return item.meta && !item.hidden
      })
      state.firstRoutes = arr
    },
    DEL_FAVORITE: (state, item) => {
      for (let i = 0, len = state.storeRoutes.length; i < len; i++) {
        if (item.path === state.storeRoutes[i].path) {
          state.storeRoutes.splice(i, 1)
          return
        }
      }
    },
    ADD_FAVORITE: (state, item) => {
      state.storeRoutes.push(
        { path: item.path, redirect: item.redirect, meta: { title: item.meta.title, icon: item.meta.icon }},
      )
    }
  },
  actions: {
    GenerateRoutes({ commit }, asyncRouter) {
      commit('SET_ROUTERS', asyncRouter)
    },
    delFavorite: ({ commit }, item) => {
      commit('DEL_FAVORITE', item)
    },
    addFavorite: ({ commit }, item) => {
      commit('ADD_FAVORITE', item)
    }
  }
}

export const filterAsyncRouter = (routers) => { // 遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = routers.filter(router => {
    if (router.component) {
      if (router.component === 'Layout') { // Layout组件特殊处理
        router.component = Layout
      } else {
        const component = router.component
        router.component = loadView(component)
      }
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children)
    }
    return true
  })
  return accessedRouters
}

export const loadView = (view) => { // 路由懒加载
  return () => import(`@/views/${view}`)
}

export default permission
